<script setup lang="ts">
import { ref, onMounted, computed, h } from 'vue';
import { NIcon, NText } from 'naive-ui';
import type { TreeOption } from 'naive-ui';
import type { DorisDatabaseTree } from '@/service/api/dataplatform/doris-storage';
import { getDatabaseTree, syncDorisMetadata } from '@/service/api/dataplatform/doris-storage';
import TableDetailDrawer from './modules/table-detail-drawer.vue';
import StorageStatisticsModal from './modules/storage-statistics-modal.vue';

defineOptions({
  name: 'DorisStorage'
});

const loading = ref(false);
const treeData = ref<DorisDatabaseTree[]>([]);
const filterText = ref('');
const selectedKeys = ref<string[]>([]);

// 表详情抽屉
const detailDrawerRef = ref();

// 存储统计弹窗
const statisticsModalRef = ref();

/** 转换树数据为 Naive UI 格式 */
function convertToTreeOptions(data: DorisDatabaseTree[]): TreeOption[] {
  return data.map(item => ({
    key: item.id,
    label: `${item.label}${item.type === 'table' && item.partitionCount ? ` (${item.partitionCount} 分区)` : ''}`,
    prefix: () => {
      const iconClass = item.type === 'database' ? 'icon-mdi-database' : item.type === 'table' ? 'icon-mdi-table' : 'icon-mdi-folder';
      return h(NIcon, { class: 'text-icon' }, { default: () => h('i', { class: iconClass }) });
    },
    children: item.children ? convertToTreeOptions(item.children) : undefined,
    isLeaf: item.type === 'table',
    _raw: item
  } as TreeOption & { _raw: DorisDatabaseTree }));
}

/** 过滤后的树数据 */
const filteredTreeData = computed(() => {
  if (!filterText.value) {
    return convertToTreeOptions(treeData.value);
  }
  
  const filterTree = (nodes: DorisDatabaseTree[]): DorisDatabaseTree[] => {
    return nodes.reduce((acc, node) => {
      const matches = node.label.toLowerCase().includes(filterText.value.toLowerCase());
      const filteredChildren = node.children ? filterTree(node.children) : [];
      
      if (matches || filteredChildren.length > 0) {
        acc.push({
          ...node,
          children: filteredChildren.length > 0 ? filteredChildren : node.children
        });
      }
      return acc;
    }, [] as DorisDatabaseTree[]);
  };
  
  return convertToTreeOptions(filterTree(treeData.value));
});

/** 加载数据库树 */
async function loadDatabaseTree() {
  try {
    loading.value = true;
    const { data } = await getDatabaseTree();
    treeData.value = data || [];
    console.log('Loaded tree data:', treeData.value);
  } catch (error) {
    console.error('加载数据库树失败:', error);
    window.$message?.error('加载数据库树失败');
  } finally {
    loading.value = false;
  }
}

/** 同步元数据 */
async function handleSync() {
  try {
    loading.value = true;
    await syncDorisMetadata();
    window.$message?.success('元数据同步成功');
    await loadDatabaseTree();
  } catch (error) {
    console.error('同步元数据失败:', error);
    window.$message?.error('同步元数据失败');
  } finally {
    loading.value = false;
  }
}

/** 树节点点击 */
function handleNodeClick(keys: string[], option: Array<TreeOption | null>) {
  if (option.length === 0 || !option[0]) return;
  
  const node = option[0] as TreeOption & { _raw?: DorisDatabaseTree };
  const rawData = node._raw;
  
  if (rawData?.type === 'table') {
    detailDrawerRef.value?.open(rawData);
  }
}

/** 查看存储统计 */
function handleViewStatistics() {
  statisticsModalRef.value?.open();
}

/** 刷新 */
function handleRefresh() {
  loadDatabaseTree();
}

onMounted(() => {
  loadDatabaseTree();
});
</script>

<template>
  <div class="h-full">
    <NCard title="Doris 存储管理" :bordered="false" class="h-full rounded-8px shadow-sm">
      <div class="h-full flex-col">
        <!-- 操作栏 -->
        <NSpace class="pb-12px" justify="space-between">
          <NSpace>
            <NButton type="primary" :loading="loading" @click="handleSync">
              <template #icon>
                <icon-mdi-refresh class="text-icon" />
              </template>
              同步元数据
            </NButton>
            <NButton @click="handleViewStatistics">
              <template #icon>
                <icon-mdi-chart-bar class="text-icon" />
              </template>
              存储统计
            </NButton>
          </NSpace>
          <NSpace>
            <NInput
              v-model:value="filterText"
              placeholder="搜索数据库、表或分区"
              clearable
              class="w-250px"
            >
              <template #prefix>
                <icon-ic-round-search class="text-icon" />
              </template>
            </NInput>
            <NButton @click="handleRefresh">
              <template #icon>
                <icon-mdi-refresh class="text-icon" />
              </template>
              刷新
            </NButton>
          </NSpace>
        </NSpace>

        <!-- 数据库树 -->
        <div class="flex-1 overflow-hidden">
          <NEmpty
            v-if="!loading && treeData.length === 0"
            description="暂无数据"
            class="h-full flex items-center justify-center"
          >
            <template #extra>
              <NText depth="3" class="text-sm">
                请先配置 Doris 数据源，然后点击"同步元数据"按钮
              </NText>
            </template>
          </NEmpty>
          <NScrollbar v-else class="h-full">
            <NSpin :show="loading">
              <NTree
                :data="filteredTreeData"
                :selected-keys="selectedKeys"
                block-line
                expand-on-click
                selectable
                @update:selected-keys="handleNodeClick"
              />
            </NSpin>
          </NScrollbar>
        </div>
      </div>
    </NCard>

    <!-- 表详情抽屉 -->
    <TableDetailDrawer ref="detailDrawerRef" />

    <!-- 存储统计弹窗 -->
    <StorageStatisticsModal ref="statisticsModalRef" />
  </div>
</template>

<style scoped>
/* Styles handled by UnoCSS utility classes */
</style>
